package cn.cena.quartz.job;

import cn.cena.order.domain.OrderPet;
import cn.cena.order.domain.OrderPetDetail;
import cn.cena.order.mapper.OrderPetDetailMapper;
import cn.cena.order.mapper.OrderPetMapper;
import cn.cena.pay.domain.PayBill;
import cn.cena.pay.mapper.PayBillMapper;
import cn.cena.pet.domain.Pet;
import cn.cena.pet.mapper.PetMapper;
import cn.cena.quartz.util.QuartzUtil;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.common.models.AlipayTradeCloseResponse;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class OrderOuttimeJob implements Job {

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private OrderPetMapper orderPetMapper;

    @Autowired
    private OrderPetDetailMapper orderPetDetailMapper;

    @Autowired
    private PetMapper petMapper;


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        // 获取数据
        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        Map<String, String> dataMap = (Map<String, String>) jobDataMap.get("params");

        String orderSn = dataMap.get("orderSn");
        String jobName = dataMap.get("jobName");

        // 查询支付订单
        PayBill payBill = payBillMapper.loadByorderSn(orderSn);
        if (payBill.getState() != PayBill.PAY_WAIT){ // 状态只是待支付才处理
            QuartzUtil.removeJob(scheduler, jobName);
        }

        // 查询订单
        OrderPet orderPet = orderPetMapper.loadByOderSn(orderSn);
        if (orderPet.getState() != OrderPet.STATE_ORDER_ONPAY){
            QuartzUtil.removeJob(scheduler, jobName);
        }

        // 更新支付订单
        payBill.setState(PayBill.PAY_CANCEL);
        Date date = new Date();
        payBill.setUpdateTime(date);
        payBillMapper.update(payBill);

        // 更新订单
        orderPet.setState(OrderPet.STATE_EXPIRE_CANCEL);
        orderPet.setLastUpdateTime(date);
        orderPetMapper.update(orderPet);

        // 更新pet表
        List<OrderPetDetail> petDetails = orderPetDetailMapper.loadByorderSn(orderSn);
        List<Long> petIds = petDetails.stream().map(petDetail->petDetail.getPetId()).collect(Collectors.toList());
        List<Pet> pets = petMapper.findByIds(petIds, Pet.STATE_ONSALE);

        pets.forEach(pet -> {
            pet.setStoreNum(pet.getStoreNum()+1);
            petMapper.update(pet);
        });

        // 调用支付宝关闭接口，关闭交易
        try {
            AlipayTradeCloseResponse response = Factory.Payment.Common().close(orderSn);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 删除订单任务
        QuartzUtil.removeJob(scheduler, jobName);
    }
}
